package org.mayanjun.code.dalint.handler;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * SpringAutodiscoveryHandler
 *
 * @author mayanjun(9/20/16)
 */
public abstract class SpringAutodiscoveryProcessor<T extends AccessHandler> implements AutodiscoveryProcessor<T>, InitializingBean, ApplicationContextAware {

	protected ApplicationContext applicationContext;

	private List<T> handlers = new CopyOnWriteArrayList<T>();

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		List<T> hs = discoverHandlers();
		if(!CollectionUtils.isEmpty(hs)) {
			this.handlers.addAll(hs);
		}
	}

	@Override
	public T getHandler(Object source) {
		for(T handler : handlers) if(handler.supports(source)) return handler;
		return null;
	}

	@Override
	public AutodiscoveryProcessor<T> setHandlers(T... handlers) {
		if(handlers != null && handlers.length > 0) {
			this.handlers.addAll(Arrays.asList(handlers));
		}
		return this;
	}

	/**
	 * Copy it
	 * @return
	 */
	public List<T> getHandlers() {
		return new ArrayList<T>(handlers);
	}
}
